package com.chinasofti.treemap;

import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;

/**
 * TreeMap统计字符串中字符个数
 * @author ndci
 *
 */
public class Demo01 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串：");
        String line = sc.nextLine();
        //定义TreeMap集合对象
        TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
        //字符串转字符数组
        char [] chs = line.toCharArray();
        //遍历字符数组->从TreeMap集合中找是否存在相应的键，如果存在，键值value+1，否则，键值设置为1.
        for(char c : chs) {
            Integer i = tm.get(c);
            if(i == null) {
                tm.put(c, 1);
            }else {
                i++;
                tm.put(c, i);
            }
        }
        //定义一个字符串缓存对象
        StringBuilder sb = new StringBuilder();
        //遍历TreeMap集合--增强for循环
        Set<Character> set = tm.keySet();
        for(Character key : set) {
            Integer value = tm.get(key);
            sb.append(key).append("(").append(value).append(")");
        }
        //字符串缓存对象转换为字符串
        String result = sb.toString();
        System.out.println(sb);
    }

}